import { _decorator, Component, Node, UITransform, Vec2 } from "cc";
import DataManager from "../../Global/DataManager";
import { IActor, InputTypeEnum, toFixed } from "../../Common";
import { EntityManager } from "../../Base/EntityManager";
import { WeaponStateManager } from "./WeaponStateManager";
import { ActorStateEnum, EventEnum } from "../../Enum";
import EventManager from "../../Global/EventManager";
const { ccclass, property } = _decorator;

@ccclass("WeaponManager")
export class WeaponManager extends EntityManager {
  owner: number;
  body: Node;
  private anchor: Node;
  private point: Node;

  start() {}

  init(data: IActor) {
    this.owner = data.id;

    this.body = this.node.getChildByName("Body");
    this.anchor = this.body.getChildByName("Anchor");
    this.point = this.anchor.getChildByName("Point");

    this.fsm = this.body.addComponent(WeaponStateManager);
    this.fsm.init(data.weaponType);
    this.state = ActorStateEnum.Idle;

    EventManager.Instance.on(
      EventEnum.WeaponShoot,
      this.handleWeaponShoot,
      this
    );
    EventManager.Instance.on(EventEnum.BulletBurn, this.handleBulletBurn, this);
  }

  handleBulletBurn(owner: number) {
    if (this.owner != owner) {
      return;
    }

    this.state = ActorStateEnum.Attack;
  }

  handleWeaponShoot() {
    if (this.owner != DataManager.Instance.myPlayerId) {
      return;
    }

    let pointWorldPos = this.point.getWorldPosition();
    let pointStagePos = DataManager.Instance.stage
      .getComponent(UITransform)
      .convertToNodeSpaceAR(pointWorldPos);
    let anchorWorldPos = this.anchor.getWorldPosition();

    let direction = new Vec2(
      pointWorldPos.x - anchorWorldPos.x,
      pointWorldPos.y - anchorWorldPos.y
    ).normalize();

    EventManager.Instance.emit(EventEnum.ClientSync, {
      owner: this.owner,
      type: InputTypeEnum.WeaponShoot,
      position: {
        x: toFixed(pointStagePos.x),
        y: toFixed(pointStagePos.y),
      },
      direction: {
        x: toFixed(direction.x),
        y: toFixed(direction.y),
      },
    });

    // DataManager.Instance.applyInput({
    //   owner: this.owner,
    //   type: InputTypeEnum.WeaponShoot,
    //   position: {
    //     x: pointStagePos.x,
    //     y: pointStagePos.y,
    //   },
    //   direction: {
    //     x: direction.x,
    //     y: direction.y,
    //   },
    // });
  }

  protected onDestroy(): void {
    EventManager.Instance.off(
      EventEnum.WeaponShoot,
      this.handleWeaponShoot,
      this
    );

    EventManager.Instance.off(
      EventEnum.BulletBurn,
      this.handleBulletBurn,
      this
    );
  }
}
